import time
import hmac
import hashlib
import base64
import urllib.parse
import requests

# 调试测试配置信息
test_cofing = {
    'secret': 'SEC95a7ab06442784d48dafb01b4e2d944e487603c1691564fe80e1e02936cfd778',
    'access_token': '0621e8ec350e0829f7996f76513edd4ca53a91f1e1dac4613ec699c76e8a9e59',
    'at_mobiles': ["18933481388"],
    'webhook_url': "https://oapi.dingtalk.com/robot/send"
}


def dingding_debug(num, case_name, api, status, msg):
    """
      通过钉钉进行报警消息推送
      :param num: 测试用例编号
      :param case_name: 测试用例名称
      :param api: 测试接口
      :param status: 响应信息
      :param msg: 报错信息
      :return: 无
      """
    # 获取当前时间戳
    timestamp = str(round(time.time() * 1000))

    # 生成签名
    secret_enc = test_cofing['secret'].encode('utf-8')
    string_to_sign = f"{timestamp}\n{test_cofing['secret']}"
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

    # 调试打印
    print(f"Timestamp: {timestamp}")
    print(f"Sign: {sign}")

    # 准备请求参数
    params = {
        'access_token': test_cofing['access_token'],
        'timestamp': timestamp,
        'sign': sign
    }
    print(f"Request params: {params}")

    # 准备消息内容
    body = {
        "msgtype": "text",
        "text": {
            "content": (
                "❗测试不通过\n"
                f"轻诉-接口用例编号：{num}\n"
                f"用例名称：{case_name}\n"
                f"接口名称：{api}\n"
                f"接口响应：{status}\n"
                f"错误信息：{msg}\n"
                "跟进回复人："
            )
        },
        "at": {
            "atMobiles": test_cofing['at_mobiles'],
            "isAtAll": False
        }
    }

    # 发送请求
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    response = requests.post(
        test_cofing['webhook_url'],
        params=params,
        headers=headers,
        json=body,
        verify=False  # 禁用SSL验证
    )

    # 打印响应信息
    print(f"Request URL: {response.url}")
    print(f"Response: {response.text}")

    return response.json()